//
//  XStatusPicturesView.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/10.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit

class XStatusPicturesView: UIView {
    var viewModel:XStatusViewModel?{
        didSet{
            calcViewSize()
            
            // 设置 urls
            urls = viewModel?.picURLs
        }
    }
    
    private var urls:[XStatusPic]?{
        didSet{
            //隐藏所有图像
            for iv in subviews{
                iv.isHidden = true
            }
            var index = 0
            for url in urls ?? []{
                //获取对应索引的imageView
                let iv = subviews[index] as! UIImageView
                //处理四张图的情况r
                if index == 1 && urls?.count == 4 {
                    index+=1
                }
                
                
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                // 判断是否是 gif，根据扩展名
                iv.subviews[0].isHidden = (((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif")
                iv.isHidden = false
                index += 1
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }

}
fileprivate extension XStatusPicturesView{
    ///设置UI
    fileprivate func setupUI(){
        
//        let color = UIColor.cz_random()
        for i in 0..<9 {
            let row:CGFloat = CGFloat(i/3)
            let col:CGFloat = CGFloat(i%3)
            
            let imageView = UIImageView(frame:CGRect(x: col * (XStatusPictureViewInnerMargin+XStatusPictureItemWidth), y: row*(XStatusPictureItemWidth+XStatusPictureViewInnerMargin)+XStatusPictureViewOutterMargin, width: XStatusPictureItemWidth, height: XStatusPictureItemWidth))
            
//            imageView.backgroundColor = color
            //设置contentMode
            imageView.clipsToBounds = true
            //填充整个view
            imageView.contentMode = .scaleAspectFill
            addSubview(imageView)
            
            
            // 让 imageView 能够接收用户交互
            imageView.isUserInteractionEnabled = true
            // 添加手势识别
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
            
            imageView.addGestureRecognizer(tap)
            // 设置 imageView 的 tag
            imageView.tag = i
            
            addGifView(iv: imageView)
        }
        
        
    }
    /// 根据视图模型的配图视图大小，调整显示内容
     func calcViewSize() {
        
        // 处理宽度
        // 1> 单图，根据配图视图的大小，修改 subviews[0] 的宽高
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.picViewSize ?? CGSize()
            
            // a) 获取第0个图像视图
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: XStatusPictureViewOutterMargin,
                             width: viewSize.width,
                             height: viewSize.height - XStatusPictureViewOutterMargin)
        } else {
            // 2> 多图(无图)，回复 subview[0] 的宽高，保证九宫格布局的完整
            
            let v = subviews[0]
            v.frame = CGRect(x: 0,
                             y: XStatusPictureViewOutterMargin,
                             width: XStatusPictureItemWidth,
                             height: XStatusPictureItemWidth)
        }
        
        // 修改高度约束
//        heightCons.constant = viewModel?.picViewSize.height ?? 0
        guard let height = viewModel?.picViewSize.height
            else{
                return
        }
        print(height)
        snp.updateConstraints { (make) in
            make.height.equalTo(Int(height))
        }

//        snp.updateConstraints { (make) in
//            make.height.equalTo(Int(height))
//        }
    }
    // MARK: - 监听方法
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
    @objc fileprivate func tapImageView(tap: UITapGestureRecognizer) {
        
        guard let iv = tap.view,
            let picURLs = viewModel?.picURLs
            else {
                return
        }
        
        var selectedIndex = iv.tag
        
        // 针对四张图处理
        if picURLs.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        
        let urls = (picURLs as NSArray).value(forKey: "largePic") as! [String]
        
        // 处理可见的图像视图数组
        var imageViewList = [UIImageView]()
        
        for iv in subviews as! [UIImageView] {
            
            if !iv.isHidden {
                imageViewList.append(iv)
            }
        }
        
        // 发送通知
        NotificationCenter.default.post(
            name: NSNotification.Name(rawValue: XStatusCellBrowserPhotoNotification),
            object: self,
            userInfo: [XStatusCellBrowserPhotoURLsKey: urls,
                       XStatusCellBrowserPhotoSelectedIndexKey: selectedIndex,
                       XStatusCellBrowserPhotoImageViewsKey: imageViewList])
    }
    /// 向图像视图添加 gif 提示图像
    private func addGifView(iv: UIImageView) {
        
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        
        iv.addSubview(gifImageView)
        
        // 自动布局
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        iv.addConstraint(NSLayoutConstraint(
            item: gifImageView,
            attribute: .right,
            relatedBy: .equal,
            toItem: iv,
            attribute: .right,
            multiplier: 1.0,
            constant: 0))
        iv.addConstraint(NSLayoutConstraint(
            item: gifImageView,
            attribute: .bottom,
            relatedBy: .equal,
            toItem: iv,
            attribute: .bottom,
            multiplier: 1.0,
            constant: 0))
    }
}
